#include "StdAfx.h"
#include "ParticleManager.h"
#include "../kernel.h"

extern Kernel* g_kernel;

#define TIME g_kernel->GetTime()

ParticleManager::ParticleManager(void)
{
    EventManager::GetInstance()->AddListener(this);
}

ParticleManager::~ParticleManager(void)
{
    //type_Emit::iterator it = m_emitters.begin();
    //for(; it != m_emitters.end(); it++ )
    //{
    //    delete *it;
    //}
    EventManager::GetInstance()->RemoveListener(this);
}


/** Update the Emitters */
void ParticleManager::Update(long dt)
{
    type_Emit::iterator it = m_emitters.begin();
    while( it != m_emitters.end() )
    {
        if ( TIME > (*it).LifeSpanOfEmitter )
        {
            //delete (*it );
            it = m_emitters.erase( it );
        }
        else
        {
            (*it).Update( dt );
            ++it;
        }
    }
}

/** Render the Emitters */
void ParticleManager::Render(IRender* r, ICamera* cam)
{
    type_Emit::iterator it = m_emitters.begin();
    for(; it != m_emitters.end(); it++ )
    {
        (*it).Render( r, cam );
    }
}

/** Remove an emitter */
void ParticleManager::RemoveEmitter( Emitter &e )
{
    type_Emit::iterator it = m_emitters.begin();
    for(; it != m_emitters.end(); it++ )
    {
        if ( (*it).GetID() == e.GetID() )
        {
            m_emitters.erase( it );
            //delete e;
            return;
        }
    } 
}

/** Handle an event */
bool ParticleManager::HandleEvent( IEvent* e )
{
    bool success = false;
    switch( e->GetType() )
    {
    case EVT_ADD_PARTICLE:
        AddEmitter( e->GetData<ParticleData>()->m_emitter );
        //std::cout << "Size: " << m_emitters.size() << "\n";
		success = true;
        break;

    case EVT_RM_PARTICLE:
        RemoveEmitter( e->GetData<ParticleData>()->m_emitter );
		success = true;
        break;
    default:
        break;
    
    };
    return success;
}